﻿'© 2004 - 2008 ActiveModules, Inc. All Rights Reserved
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text.RegularExpressions
Imports System.Xml

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <DefaultProperty("Text"), ToolboxData("<{0}:TopicView runat=server></{0}:TopicView>")> _
    Public Class TopicView
        Inherits ForumBase
#Region "Private Members"
        Private _metaTemplate As String = "[META][TITLE][TOPICSUBJECT] - [PORTALNAME] - [PAGENAME] - [GROUPNAME] - [FORUMNAME][/TITLE][DESCRIPTION][BODY:255][/DESCRIPTION][KEYWORDS][TAGS][VALUE][/KEYWORDS][/META]"
        Private _metaTitle As String = String.Empty
        Private _metaDescription As String = String.Empty
        Private _metaKeywords As String = String.Empty
        Private ForumName As String
        Private GroupName As String
        'Private ForumGroupId As Integer = 0
        Private TopicTemplateId As Integer
        Private drForum As DataRow
        Private drSecurity As DataRow
        Private dtTopic As DataTable
        Private dtAttach As DataTable
        Private bView As Boolean = False
        Private bRead As Boolean = False
        Private bCreate As Boolean = False
        Private bPoll As Boolean = False
        Private bAttach As Boolean = False
        Private bTrust As Boolean = False
        Private bReply As Boolean = False
        Private bDelete As Boolean = False
        Private bEdit As Boolean = False
        Private bLock As Boolean = False
        Private bPin As Boolean = False
        Private bSubscribe As Boolean = False
        Private bModApprove As Boolean = False
        Private bModMove As Boolean = False
        Private bModSplit As Boolean = False
        Private bModDelete As Boolean = False
        Private bModEdit As Boolean = False
        Private bAllowRSS As Boolean = False
        Private RowIndex As Integer = 0
        Private PageSize As Integer = 20
        Private MyTheme As String = "_default"
        Private MyThemePath As String = String.Empty
        Private bLocked As Boolean = False
        Private TopicType As Integer = 0
        Private TopicSubject As String = String.Empty
        Private TopicDescription As String = String.Empty
        Private ViewCount As Integer = 0
        Private ReplyCount As Integer = 0
        Private RowCount As Integer = 0
        Private StatusId As Integer = 0
        Private TopicAuthorId As Integer = 0
        Private TopicAuthorDisplayName As String = String.Empty
        Private TopicDateCreated As String = String.Empty
        Private MemberListMode As String = String.Empty
        Private ProfileVisibility As String = String.Empty
        Private UserNameDisplay As String = String.Empty
        Private DisableUserProfiles As Boolean = False
        Private AllowAvatars As Boolean = False
        Private bAllowSignatures As Boolean = True
        Private EnablePoints As Boolean = False
        Private TrustDefault As Boolean = False
        Private IsTrusted As Boolean = False
        Private TopicRating As Integer = 0
        Private AllowHTML As Boolean = False
        Private AllowScript As Boolean = False
        Private AllowSubscribe As Boolean = False
        Private NextTopic As Integer = 0
        Private PrevTopic As Integer = 0
        Private IsSubscribedTopic As Boolean = False
        Private IsSubscribedForum As Boolean = False
        Private LastPostDate As String
        Private LastPostAuthor As New Author
        Private DefaultSort As String = "ASC"
        Private AllowTags As Boolean = False
        Private EditInterval As Integer = 0
        Private Tags As String = String.Empty
        Private TopicURL As String = String.Empty
        Private _template As String = String.Empty
        Private _pageSize As Integer = -1
        Private _defaultSort As String = String.Empty
        Private TopicData As String = String.Empty
        Private SkipBindTopic As Boolean = False
        Private sGroupURL As String = String.Empty
        Private sForumURL As String = String.Empty
        Private sTopicURL As String = String.Empty
        Private UseListActions As Boolean = False
        Private NoPaging As Boolean = False
#End Region
#Region "Public Properties"
        Public Property TopicTemplate() As String
            Get
                Return _template
            End Get
            Set(ByVal value As String)
                _template = value
            End Set
        End Property
        Public Property OptPageSize() As Integer
            Get
                Return _pageSize
            End Get
            Set(ByVal value As Integer)
                _pageSize = value
            End Set
        End Property
        Public WriteOnly Property OptDefaultSort() As String
            Set(ByVal value As String)
                _defaultSort = value
            End Set
        End Property
        Public Property MetaTemplate() As String
            Get
                Return _metaTemplate
            End Get
            Set(ByVal value As String)
                _metaTemplate = value
            End Set
        End Property
        Public Property MetaTitle() As String
            Get
                Return _metaTitle
            End Get
            Set(ByVal value As String)
                _metaTitle = value
            End Set
        End Property
        Public Property MetaDescription() As String
            Get
                Return _metaDescription
            End Get
            Set(ByVal value As String)
                _metaDescription = value
            End Set
        End Property
        Public Property MetaKeywords() As String
            Get
                Return _metaKeywords
            End Get
            Set(ByVal value As String)
                _metaKeywords = value
            End Set
        End Property
#End Region
#Region "Protected Controls"
        Protected WithEvents ctlForumJump As New DotNetNuke.Modules.ActiveForums.af_quickjump
        Protected WithEvents ctlPoll As New DotNetNuke.Modules.ActiveForums.af_polls
        Protected WithEvents ctlQuickReply As New DotNetNuke.Modules.ActiveForums.af_quickreplyform
        Protected WithEvents ctlTopicSort As New DotNetNuke.Modules.ActiveForums.af_topicsorter
        Protected WithEvents ctlTopicStatus As New DotNetNuke.Modules.ActiveForums.af_topicstatus
        Protected WithEvents cbTopicActions As New DotNetNuke.Modules.ActiveForums.Controls.Callback
        Protected WithEvents plhTopic As New PlaceHolder
#End Region
#Region "Event Handlers"
        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            If ForumInfo Is Nothing Then
                Dim fc As New ForumController
                ForumInfo = fc.Forums_Get(PortalId, ForumModuleId, ForumId, UserId, True, False, TopicId)
            End If

            'Me.EnableViewState = False

        End Sub
        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try

                Dim sURL As String = Request.RawUrl
                If Not Page.IsPostBack Then
                    If sURL.Contains("view") And sURL.Contains("postid") And sURL.Contains("forumid") Then
                        sURL = sURL.Replace("view", ParamKeys.ViewType)
                        sURL = sURL.Replace("postid", ParamKeys.TopicId)
                        sURL = sURL.Replace("forumid", ParamKeys.ForumId)
                        Response.Status = "301 Moved Permanently"
                        Response.AddHeader("Location", sURL)
                    End If
                    If ForumId < 1 Then
                        Response.Redirect(Utilities.NavigateUrl(TabId))
                    End If
                End If
                If Not Request.Params(ParamKeys.FirstNewPost) Is Nothing Then
                    If IsNumeric(Request.Params(ParamKeys.FirstNewPost)) Then
                        Dim cjid As Integer = -1
                        cjid = DataProvider.Instance.Utility_GetFirstUnRead(TopicId, CInt(Request.Params(ParamKeys.FirstNewPost)))
                        If cjid > 0 And cjid > CInt(Request.Params(ParamKeys.FirstNewPost)) Then
                            Dim tURL As String = Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=topic", ParamKeys.ContentJumpId & "=" & cjid})
                            If MainSettings.UseShortUrls Then
                                tURL = Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & cjid})
                            End If
                            Response.Redirect(tURL)
                        End If
                    End If


                End If
                Me.AppRelativeVirtualPath = "~/"
                MyTheme = MainSettings.Theme
                MyThemePath = Page.ResolveUrl("~/DesktopModules/ActiveForums/themes/" & MyTheme)
                UserNameDisplay = MainSettings.UserNameDisplay
                DisableUserProfiles = False
                AllowAvatars = True
                EnablePoints = MainSettings.EnablePoints


                EditInterval = MainSettings.EditInterval

                If MainSettings.AllowSignatures = 1 Or MainSettings.AllowSignatures = 2 Then
                    If UserId > 0 Then
                        bAllowSignatures = CBool(IIf(UserPrefHideSigs, False, True))
                    Else
                        bAllowSignatures = True
                    End If
                End If
                If AllowAvatars = True Then
                    If UserId > 0 Then
                        AllowAvatars = CBool(IIf(UserPrefHideAvatars, False, True))
                    End If
                End If
                Dim sSort As String = "ASC"

                If ForumUser.Profile.PrefDefaultSort.Trim = "ASC" Or ForumUser.Profile.PrefDefaultSort.Trim = "DESC" Then
                    sSort = ForumUser.Profile.PrefDefaultSort.Trim
                    DefaultSort = sSort
                End If
                If Not Request.Params(ParamKeys.Sort) Is Nothing Then
                    sSort = Request.Params(ParamKeys.Sort)
                    If Not sSort.ToUpper = "ASC" And Not sSort.ToUpper = "DESC" Then
                        sSort = "ASC"
                    End If
                End If
                If _defaultSort = String.Empty Then
                    DefaultSort = sSort
                Else
                    DefaultSort = _defaultSort
                End If
                'If Not IsCallback() Then
                LoadData(PageId)
                If Not SkipBindTopic Then
                    BindTopic()
                End If

                If Request.IsAuthenticated Then
                    AllowSubscribe = bSubscribe
                Else
                    AllowSubscribe = False
                End If
                'End If
                Dim sb As New Text.StringBuilder
                'Dim cbscript As String = "function afcbtopic(params){" & cbTopicActions.ClientID & ".Callback(params);};function afcbtopiccomplete(){window.scrollTo(0,0);window.top.afreload();};"
                'If bModDelete Or bDelete Then
                '    cbscript &= "function afcbdelpost(fid,tid,pid){if (confirm('" & GetSharedResource("[RESX:Confirm:Delete]") & "')){af_showLoad();" & cbTopicLoader.ClientID & ".Callback('delpost',pid,tid,fid);};};"
                'End If

                'Page.ClientScript.RegisterClientScriptBlock(Page.GetType, "cbscript", cbscript, True)
                Try
                    Environment.UpdateMeta(Me.BasePage, MetaTitle, MetaDescription, MetaKeywords)

                Catch ex As Exception

                End Try

            Catch ex As Exception
                RenderMessage("[RESX:Error:LoadingTopic]", ex.Message, ex)

            End Try
        End Sub
       
#End Region
#Region "Private Methods"

        Private Sub LoadData(ByVal PageId As Integer)
            If OptPageSize = -1 Then
                PageSize = MainSettings.PageSize
                If UserId > 0 Then
                    PageSize = UserDefaultPageSize
                End If
                If PageSize < 5 Then
                    PageSize = 10
                End If
            Else
                PageId = 1
                PageSize = Integer.MaxValue
            End If


            If PageId = 1 Then
                RowIndex = 0
            Else
                RowIndex = ((PageId * PageSize) - PageSize)
            End If
            Dim sURL As String = Request.RawUrl
            If Not Request.QueryString("dnnprintmode") Is Nothing Or OptPageSize > 0 Then
                RowIndex = 0
                PageSize = Integer.MaxValue
            End If
            Dim defaultTemplateId As Integer = ForumInfo.TopicTemplateId
            If DefaultTopicViewTemplateId >= 0 Then
                defaultTemplateId = DefaultTopicViewTemplateId
            End If
            TopicTemplateId = defaultTemplateId
            Dim stmp As String = DataCache.GetCachedTemplate(MainSettings.TemplateCache, ModuleId, "TopicView", defaultTemplateId)
            If stmp.Contains("[NOPAGING]") Then
                PageId = 1
                RowIndex = 0
                PageSize = Integer.MaxValue
                NoPaging = True
            End If
            If stmp.Contains("[NOTOOLBAR]") Then
                If HttpContext.Current.Items.Contains("ShowToolbar") Then
                    HttpContext.Current.Items("ShowToolbar") = False
                Else
                    HttpContext.Current.Items.Add("ShowToolbar", False)
                End If
                stmp = stmp.Replace("[NOTOOLBAR]", String.Empty)
            End If
            If stmp.ToLowerInvariant.Contains("am:topicnavigator") Then
                stmp = stmp.Replace("[PORTALID]", PortalId.ToString)
                stmp = stmp.Replace("[MODULEID]", ForumModuleId.ToString)
                stmp = stmp.Replace("[TABID]", ForumTabId.ToString)
                Me.Controls.Add(Me.ParseControl(stmp))
                LinkControls(Me.Controls)
                SkipBindTopic = True
                Exit Sub
            End If
            Dim ds As DataSet = DataProvider.Instance.UI_TopicView(PortalId, ModuleId, ForumId, TopicId, UserId, RowIndex, PageSize, UserInfo.IsSuperUser, DefaultSort)
            If ds.Tables.Count > 0 Then
                If ds.Tables(0).Rows.Count = 0 Then
                    Response.Redirect(Utilities.NavigateUrl(TabId))
                End If

                drForum = ds.Tables(0).Rows(0)
                drSecurity = ds.Tables(1).Rows(0)
                dtTopic = ds.Tables(2)
                If dtTopic.Rows.Count = 0 And PageId > 1 Then
                    If MainSettings.UseShortUrls Then
                        Response.Redirect(Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.TopicId & "=" & TopicId}))
                    Else
                        Response.Redirect(Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & TopicId}))
                    End If
                ElseIf dtTopic.Rows.Count = 0 And PageId = 1 Then
                    If MainSettings.UseShortUrls Then
                        Response.Redirect(Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId}))
                    Else
                        Response.Redirect(Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topics}))
                    End If
                End If

                dtAttach = ds.Tables(3)
                bView = Permissions.HasPerm(drSecurity("CanView").ToString, ForumUser.UserRoles)
                bRead = Permissions.HasPerm(drSecurity("CanRead").ToString, ForumUser.UserRoles)
                bCreate = Permissions.HasPerm(drSecurity("CanCreate").ToString, ForumUser.UserRoles)
                bEdit = Permissions.HasPerm(drSecurity("CanEdit").ToString, ForumUser.UserRoles)
                bDelete = Permissions.HasPerm(drSecurity("CanDelete").ToString, ForumUser.UserRoles)
                bReply = Permissions.HasPerm(drSecurity("CanReply").ToString, ForumUser.UserRoles)
                bPoll = Permissions.HasPerm(drSecurity("CanPoll").ToString, ForumUser.UserRoles)
                bAttach = Permissions.HasPerm(drSecurity("CanAttach").ToString, ForumUser.UserRoles)
                bSubscribe = Permissions.HasPerm(drSecurity("CanSubscribe").ToString, ForumUser.UserRoles)
                bModMove = Permissions.HasPerm(drSecurity("CanModMove").ToString, ForumUser.UserRoles)
                bModSplit = Permissions.HasPerm(drSecurity("CanModSplit").ToString, ForumUser.UserRoles)
                bModDelete = Permissions.HasPerm(drSecurity("CanModDelete").ToString, ForumUser.UserRoles)
                bModApprove = Permissions.HasPerm(drSecurity("CanModApprove").ToString, ForumUser.UserRoles)
                bTrust = Permissions.HasPerm(drSecurity("CanTrust").ToString, ForumUser.UserRoles)
                bModEdit = Permissions.HasPerm(drSecurity("CanModEdit").ToString, ForumUser.UserRoles)
                IsTrusted = Utilities.IsTrusted(ForumInfo.DefaultTrustValue, ForumUser.TrustLevel, Permissions.HasPerm(ForumInfo.Security.Trust, ForumUser.UserRoles))


                If bRead Then
                    ForumName = drForum("ForumName").ToString
                    GroupName = drForum("GroupName").ToString
                    ForumGroupId = CInt(drForum("ForumGroupId"))
                    TopicTemplateId = CInt(drForum("TopicTemplateId"))
                    bAllowRSS = CBool(drForum("AllowRSS"))
                    bLocked = CBool(drForum("IsLocked"))
                    TopicType = CInt(drForum("TopicType"))
                    StatusId = CInt(drForum("StatusId"))
                    TopicSubject = CStr(drForum("Subject"))
                    TopicDescription = Utilities.StripHTMLTag(drForum("Body").ToString)
                    Tags = drForum("Tags").ToString
                    ViewCount = CInt(drForum("ViewCount"))
                    ReplyCount = CInt(drForum("ReplyCount"))
                    TopicAuthorId = CInt(drForum("AuthorId"))
                    TopicAuthorDisplayName = drForum("TopicAuthor").ToString
                    TopicRating = CInt(drForum("TopicRating"))
                    AllowHTML = CBool(drForum("AllowHTML"))
                    AllowScript = CBool(drForum("AllowScript"))
                    AllowTags = CBool(drForum("AllowTags"))
                    RowCount = CInt(drForum("ReplyCount")) + 1
                    NextTopic = CInt(drForum("NextTopic"))
                    PrevTopic = CInt(drForum("PrevTopic"))
                    LastPostDate = GetDate(CDate(drForum("LastPostDate")))
                    LastPostAuthor.AuthorId = CInt(drForum("LastPostAuthorId"))
                    LastPostAuthor.DisplayName = drForum("LastPostDisplayName").ToString
                    LastPostAuthor.FirstName = drForum("LastPostFirstName").ToString
                    LastPostAuthor.LastName = drForum("LastPostLastName").ToString
                    LastPostAuthor.Username = drForum("LastPostUserName").ToString
                    TopicURL = drForum("URL").ToString
                    TopicDateCreated = Utilities.GetDate(CDate(drForum("DateCreated").ToString), ForumModuleId, TimeZoneOffset)
                    TopicData = drForum("TopicData").ToString
                    If UserId > 0 Then
                        IsSubscribedTopic = CBool(IIf(CInt(drForum("IsSubscribedTopic")) > 0, True, False))
                        IsSubscribedForum = CBool(IIf(CInt(drForum("IsSubscribedForum")) > 0, True, False))
                    End If
                    If Not Page.IsPostBack Then
                        If Not Request.Params("ptarget") Is Nothing Or Not Request.Params(ParamKeys.ContentJumpId) Is Nothing Then
                            Dim intPages As Integer
                            intPages = CType(System.Math.Ceiling(RowCount / PageSize), Integer)
                            Dim sTarget As String = ""
                            If Not Request.Params("ptarget") Is Nothing Then
                                sTarget = "#" & Request.Params("ptarget")
                            ElseIf Not Request.Params(ParamKeys.ContentJumpId) Is Nothing Then
                                sTarget = "#" & Request.Params(ParamKeys.ContentJumpId)

                            End If
                            If Request.IsAuthenticated Then
                                If MainSettings.URLRewriteEnabled And Request.QueryString("asg") Is Nothing And Not String.IsNullOrEmpty(TopicURL) Then
                                    Dim db As New Data.Common
                                    sURL = db.GetUrl(ModuleId, ForumGroupId, ForumId, TopicId, Me.UserId, CInt(Request.Params(ParamKeys.ContentJumpId)))
                                    If Not sURL.StartsWith("/") Then
                                        sURL = "/" & sURL
                                    End If
                                    If Not sURL.EndsWith("/") Then
                                        sURL &= "/"
                                    End If
                                    sURL &= sTarget
                                Else
                                    sURL = String.Empty
                                End If
                                If String.IsNullOrEmpty(sURL) Then
                                    Dim Params As String() = {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=" & Views.Topic}
                                    If MainSettings.UseShortUrls Then
                                        Params = New String() {ParamKeys.TopicId & "=" & TopicId}
                                    End If
                                    If intPages > 1 And NoPaging = False Then
                                        Params = Utilities.AddParams(ParamKeys.PageJumpId & "=" & intPages, Params)
                                    End If
                                    sURL = Utilities.NavigateUrl(TabId, "", Params) & sTarget
                                End If

                                Response.Redirect(sURL)
                            Else
                                If MainSettings.URLRewriteEnabled And Not String.IsNullOrEmpty(TopicURL) Then
                                    Dim db As New Data.Common
                                    sURL = db.GetUrl(ModuleId, ForumGroupId, ForumId, TopicId, -1, CInt(Request.Params(ParamKeys.ContentJumpId)))
                                    If Not sURL.StartsWith("/") Then
                                        sURL = "/" & sURL
                                    End If
                                    If Not sURL.EndsWith("/") Then
                                        sURL &= "/"
                                    End If
                                    sURL &= sTarget
                                Else
                                    sURL = String.Empty
                                End If
                                If String.IsNullOrEmpty(sURL) Then
                                    Dim Params As String() = {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=" & Views.Topic}
                                    If MainSettings.UseShortUrls Then
                                        Params = New String() {ParamKeys.TopicId & "=" & TopicId}
                                    End If
                                    If intPages > 1 And NoPaging = False Then
                                        Params = Utilities.AddParams(ParamKeys.PageId & "=" & intPages, Params)
                                    End If
                                    sURL = Utilities.NavigateUrl(TabId, "", Params) & sTarget
                                End If

                                Response.Status = "301 Moved Permanently"
                                Response.AddHeader("Location", sURL)
                            End If
                        End If
                    End If
                Else
                    Dim settings As DotNetNuke.Entities.Portals.PortalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings
                    If settings.LoginTabId > 0 Then
                        'Response.Redirect(Utilities.NavigateUrl(settings.LoginTabId, "", "returnUrl=" & Request.RawUrl.ToString), True)
                        Response.Redirect(DotNetNuke.Common.NavigateURL(settings.LoginTabId, "", "returnUrl=" & Request.RawUrl.ToString), True)
                    Else
                        Response.Redirect(Utilities.NavigateUrl(TabId, "", "ctl=login&returnUrl=" & Request.RawUrl.ToString), True)
                        'Response.Redirect(DotNetNuke.Common.NavigateURL(TabId, "", "returnUrl=" & Request.RawUrl.ToString), True)
                    End If

                End If


            Else
                Response.Redirect(NavigateUrl(TabId), True)
            End If
        End Sub
        Private Sub BindTopic()
            Dim sOutput As String = ""
            Dim bFullTopic As Boolean = True
            If UseTemplatePath And Not TemplatePath = String.Empty Then
                sOutput = Utilities.GetFileContent(TemplatePath & "TopicView.htm")
                sOutput = Utilities.ParseSpacer(sOutput)
            ElseIf TopicTemplate = String.Empty Then
                sOutput = DataCache.GetCachedTemplate(MainSettings.TemplateCache, ModuleId, "TopicView", TopicTemplateId)
            Else
                bFullTopic = False
                sOutput = TopicTemplate
                sOutput = Utilities.ParseSpacer(sOutput)
            End If
            If sOutput.Contains("[POSTINFO]") And ForumInfo.ProfileTemplateId > 0 Then
                sOutput = sOutput.Replace("[POSTINFO]", DataCache.GetCachedTemplate(MainSettings.TemplateCache, ModuleId, "ProfileInfo", ForumInfo.ProfileTemplateId))
            End If
            If sOutput.Contains("[META]") Then
                MetaTemplate = TemplateUtils.GetTemplateSection(sOutput, "[META]", "[/META]")
                sOutput = TemplateUtils.ReplaceSubSection(sOutput, String.Empty, "[META]", "[/META]")
            End If
            sOutput = sOutput.Replace("[PORTALID]", PortalId.ToString)
            sOutput = sOutput.Replace("[MODULEID]", ForumModuleId.ToString)
            sOutput = sOutput.Replace("[TABID]", ForumTabId.ToString)
            sOutput = sOutput.Replace("[TOPICID]", TopicId.ToString)
            sOutput = sOutput.Replace("[AF:CONTROL:FORUMID]", ForumId.ToString)
            sOutput = sOutput.Replace("[AF:CONTROL:FORUMGROUPID]", ForumGroupId.ToString)
            sOutput = sOutput.Replace("[AF:CONTROL:PARENTFORUMID]", ParentForumId.ToString)

         
            If sOutput.Contains("<am:TopicsNavigator") Then
                Me.Controls.Add(Me.ParseControl(sOutput))
                LinkControls(Me.Controls)
            Else
                If sOutput.Contains("[AF:PROPERTIES") Then

                    If String.IsNullOrEmpty(TopicData) Then
                        sOutput = TemplateUtils.ReplaceSubSection(sOutput, String.Empty, "[AF:PROPERTIES]", "[/AF:PROPERTIES]")
                    Else
                        Dim sPropTemplate As String = TemplateUtils.GetTemplateSection(sOutput, "[AF:PROPERTIES]", "[/AF:PROPERTIES]")
                        Dim sProps As String = String.Empty
                        Dim xDoc As New XmlDocument
                        xDoc.LoadXml(TopicData)
                        If Not xDoc Is Nothing Then
                            Dim xRoot As System.Xml.XmlNode = xDoc.DocumentElement
                            Dim xNodeList As System.Xml.XmlNodeList = xRoot.SelectNodes("//properties/property")
                            If xNodeList.Count > 0 Then
                                Dim i As Integer = 0
                                For i = 0 To xNodeList.Count - 1
                                    Dim tmp As String = sPropTemplate
                                    Dim pName As String = Utilities.HTMLDecode(xNodeList(i).ChildNodes.Item(0).InnerText)
                                    Dim pValue As String = Utilities.HTMLDecode(xNodeList(i).ChildNodes.Item(1).InnerText)
                                    tmp = tmp.Replace("[AF:PROPERTY:LABEL]", "[RESX:" & pName & "]")
                                    tmp = tmp.Replace("[AF:PROPERTY:VALUE]", pValue)
                                    sOutput = sOutput.Replace("[AF:PROPERTY:" & pName & ":LABEL]", Utilities.GetSharedResource("[RESX:" & pName & "]"))
                                    sOutput = sOutput.Replace("[AF:PROPERTY:" & pName & ":VALUE]", pValue)
                                    Dim pValueKey As String = String.Empty
                                    If Not String.IsNullOrEmpty(pValue) Then
                                        pValueKey = Utilities.CleanName(pValue).ToLowerInvariant
                                    End If
                                    sOutput = sOutput.Replace("[AF:PROPERTY:" & pName & ":VALUEKEY]", pValueKey)
                                    sProps &= tmp
                                Next
                            End If
                        End If
                        sOutput = TemplateUtils.ReplaceSubSection(sOutput, sProps, "[AF:PROPERTIES]", "[/AF:PROPERTIES]")

                    End If


                End If
                'Parse Meta Template
                If Not String.IsNullOrEmpty(MetaTemplate) Then
                    MetaTemplate = MetaTemplate.Replace("[FORUMNAME]", ForumName)
                    MetaTemplate = MetaTemplate.Replace("[GROUPNAME]", GroupName)
                    Dim pageName As String = String.Empty
                    Dim settings As DotNetNuke.Entities.Portals.PortalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings
                    If (settings.ActiveTab.Title.Length = 0) Then
                        pageName = Server.HtmlEncode(settings.ActiveTab.TabName)
                    Else
                        pageName = Server.HtmlEncode(settings.ActiveTab.Title)
                    End If
                    MetaTemplate = MetaTemplate.Replace("[PAGENAME]", pageName)
                    MetaTemplate = MetaTemplate.Replace("[PORTALNAME]", settings.PortalName)
                    MetaTemplate = MetaTemplate.Replace("[TAGS]", Tags)
                    If MetaTemplate.Contains("[TOPICSUBJECT:") Then
                        Dim pattern As String = "(\[TOPICSUBJECT:(.+?)\])"
                        Dim regExp As New Regex(pattern)
                        Dim matches As MatchCollection
                        matches = regExp.Matches(MetaTemplate)
                        For Each m As Match In matches
                            Dim iLen As Integer = CInt(m.Groups(2).Value)
                            If TopicSubject.Length > iLen Then
                                MetaTemplate = MetaTemplate.Replace(m.Value, TopicSubject.Substring(0, iLen) & "...")
                            Else
                                MetaTemplate = MetaTemplate.Replace(m.Value, Utilities.StripHTMLTag(TopicSubject))
                            End If
                        Next m
                    End If
                    MetaTemplate = MetaTemplate.Replace("[TOPICSUBJECT]", Utilities.StripHTMLTag(TopicSubject))
                    If MetaTemplate.Contains("[BODY:") Then
                        Dim pattern As String = "(\[BODY:(.+?)\])"
                        Dim regExp As New Regex(pattern)
                        Dim matches As MatchCollection
                        matches = regExp.Matches(MetaTemplate)
                        For Each m As Match In matches
                            Dim iLen As Integer = CInt(m.Groups(2).Value)
                            If TopicDescription.Length > iLen Then
                                MetaTemplate = MetaTemplate.Replace(m.Value, TopicDescription.Substring(0, iLen) & "...")
                            Else
                                MetaTemplate = MetaTemplate.Replace(m.Value, TopicDescription)
                            End If
                        Next m
                    End If
                    MetaTemplate = MetaTemplate.Replace("[BODY]", TopicDescription)

                    MetaTitle = TemplateUtils.GetTemplateSection(MetaTemplate, "[TITLE]", "[/TITLE]").Replace("[TITLE]", String.Empty).Replace("[/TITLE]", String.Empty)
                    MetaDescription = TemplateUtils.GetTemplateSection(MetaTemplate, "[DESCRIPTION]", "[/DESCRIPTION]").Replace("[DESCRIPTION]", String.Empty).Replace("[/DESCRIPTION]", String.Empty)
                    MetaKeywords = TemplateUtils.GetTemplateSection(MetaTemplate, "[KEYWORDS]", "[/KEYWORDS]").Replace("[KEYWORDS]", String.Empty).Replace("[/KEYWORDS]", String.Empty)
                End If
                Dim ctlUtils As New ControlUtils
                sGroupURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, String.Empty, ForumInfo.ForumGroupId, -1, -1, -1, String.Empty, 1, SocialGroupId)
                sForumURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumInfo.ForumGroupId, ForumInfo.ForumID, -1, -1, String.Empty, 1, SocialGroupId)
                sTopicURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumInfo.ForumGroupId, ForumInfo.ForumID, TopicId, TopicURL, -1, -1, String.Empty, 1, SocialGroupId)

                If MainSettings.UseSkinBreadCrumb Then
                    Dim sCrumb As String = "<a href=""" & sGroupURL & """>" & GroupName & "</a>|"
                    sCrumb &= "<a href=""" & sForumURL & """>" & ForumName & "</a>"
                    sCrumb &= "|<a href=""" & sTopicURL & """>" & TopicSubject & "</a>"
                    

                    If Environment.UpdateBreadCrumb(Page.Controls, sCrumb) Then
                        sOutput = sOutput.Replace("<div  class=""afcrumb"">[FORUMMAINLINK] > [FORUMGROUPLINK] > [FORUMLINK]</div>", String.Empty)
                    End If

                End If
                'Parse Common Controls First
                sOutput = ParseControls(sOutput)
                'Parse Topics and Add to controls
                Dim topics As String = TemplateUtils.GetTemplateSection(sOutput, "[AF:CONTROL:CALLBACK]", "[/AF:CONTROL:CALLBACK]")
                topics = ParseTopic(topics)

                topics = "<%@ Register TagPrefix=""am"" Namespace=""DotNetNuke.Modules.ActiveForums.Controls"" Assembly=""DotNetNuke.Modules.ActiveForums"" %>" & topics

                If MainSettings.ProfileType = ProfileTypes.Social Then
                    If Not topics.Contains(Globals.SocialRegisterTag) Then
                        topics = Globals.SocialRegisterTag & topics
                    End If
                End If

                topics = Utilities.LocalizeControl(topics)
                If bFullTopic Then
                    sOutput = TemplateUtils.ReplaceSubSection(sOutput, "<asp:placeholder id=""plhTopicCallback"" runat=""server"" />", "[AF:CONTROL:CALLBACK]", "[/AF:CONTROL:CALLBACK]")
                    'sOutput = ParseTopic(sOutput)
                    sOutput = Utilities.LocalizeControl(sOutput)
                    sOutput = Utilities.StripTokens(sOutput)
                    Me.Controls.Add(Me.ParseControl(sOutput))
                End If



                Dim plhCB As PlaceHolder = CType(Me.FindControl("plhTopicCallback"), PlaceHolder)
                If Not plhCB Is Nothing Then
                    plhTopic.Controls.Clear()
                    plhTopic.ID = "plhTopic"

                    plhTopic.Controls.Add(Me.ParseControl(topics))
                    plhCB.Controls.Add(plhTopic)
                    'cbTopicLoader = New DotNetNuke.Modules.ActiveForums.Controls.Callback

                    'cbTopicLoader.OnCallbackComplete = "af_clearLoad"
                    'Dim ct As New Modules.ActiveForums.Controls.CallBackContent
                    'ct.Controls.Add(plhTopic)
                    'cbTopicLoader.Content = ct
                    'plhCB.Controls.Add(cbTopicLoader)
                Else
                    plhTopic.Controls.Clear()
                    plhTopic.ID = "plhTopic"
                    plhTopic.Controls.Add(Me.ParseControl(topics))
                    Me.Controls.Add(plhTopic)

                End If
                'Add helper controls
                'Quick Jump DropDownList
                Dim plh As PlaceHolder = CType(Me.FindControl("plhQuickJump"), PlaceHolder)
                If Not plh Is Nothing Then
                    plh.Controls.Clear()
                    ctlForumJump = New af_quickjump
                    ctlForumJump.ModuleConfiguration = Me.ModuleConfiguration
                    ctlForumJump.MOID = ModuleId
                    ctlForumJump.dtForums = Nothing
                    ctlForumJump.ForumId = ForumId
                    ctlForumJump.EnableViewState = False
                    If ForumId > 0 Then
                        ctlForumJump.ForumInfo = ForumInfo
                    End If
                    If Not plh.Controls.Contains(ctlForumJump) Then
                        plh.Controls.Add(ctlForumJump)
                    End If

                End If
                plh = Nothing
                ''Poll Container
                plh = CType(Me.FindControl("plhPoll"), PlaceHolder)
                If Not plh Is Nothing Then
                    ctlPoll = New af_polls
                    ctlPoll.ModuleConfiguration = Me.ModuleConfiguration
                    ctlPoll.TopicId = TopicId
                    ctlPoll.ForumId = ForumId
                    plh.Controls.Add(ctlPoll)
                End If
                'Quick Reply
                If bReply And bLocked = False Then
                    plh = CType(Me.FindControl("plhQuickReply"), PlaceHolder)
                    If Not plh Is Nothing Then
                        ctlQuickReply = CType(LoadControl("~/DesktopModules/ActiveForums/controls/af_quickreply.ascx"), af_quickreplyform)
                        ctlQuickReply.ModuleConfiguration = Me.ModuleConfiguration
                        'ctlQuickReply.CanReply = bReply
                        ctlQuickReply.CanTrust = bTrust
                        ctlQuickReply.ModApprove = bModApprove
                        ctlQuickReply.IsTrusted = IsTrusted
                        'ctlQuickReply.ThemePath = MyThemePath
                        ctlQuickReply.Subject = TopicSubject
                        ctlQuickReply.AllowSubscribe = AllowSubscribe
                        ctlQuickReply.AllowHTML = AllowHTML
                        ctlQuickReply.AllowScripts = AllowScript
                        ctlQuickReply.ForumId = ForumId
                        ctlQuickReply.SocialGroupId = SocialGroupId
                        ctlQuickReply.ForumModuleId = ForumModuleId
                        ctlQuickReply.ForumTabId = TabId
                        If ForumId > 0 Then
                            ctlQuickReply.ForumInfo = ForumInfo
                        End If
                        If Not plh.Controls.Contains(ctlQuickReply) Then
                            plh.Controls.Add(ctlQuickReply)
                        End If

                    End If
                End If
                plh = CType(Me.FindControl("plhTopicSort"), PlaceHolder)
                If Not plh Is Nothing Then
                    plh.Controls.Clear()
                    ctlTopicSort = CType(LoadControl("~/DesktopModules/ActiveForums/controls/af_topicsort.ascx"), af_topicsorter)
                    ctlTopicSort.ModuleConfiguration = Me.ModuleConfiguration
                    ctlTopicSort.ForumId = ForumId
                    ctlTopicSort.DefaultSort = DefaultSort
                    If ForumId > 0 Then
                        ctlTopicSort.ForumInfo = ForumInfo
                    End If
                    If Not plh.Controls.Contains(ctlTopicSort) Then
                        plh.Controls.Add(ctlTopicSort)
                    End If

                End If
                plh = CType(Me.FindControl("plhStatus"), PlaceHolder)
                If Not plh Is Nothing Then
                    plh.Controls.Clear()
                    ctlTopicStatus = CType(LoadControl("~/DesktopModules/ActiveForums/controls/af_topicstatus.ascx"), af_topicstatus)
                    ctlTopicStatus.ModuleConfiguration = Me.ModuleConfiguration
                    ctlTopicStatus.Status = StatusId
                    ctlTopicStatus.ForumId = ForumId
                    If ForumId > 0 Then
                        ctlTopicStatus.ForumInfo = ForumInfo
                    End If
                    If Not plh.Controls.Contains(ctlTopicStatus) Then
                        plh.Controls.Add(ctlTopicStatus)
                    End If

                End If
                'Dim sPage As String = "function afPageTopic(page){"
                'sPage &= "af_showLoad();window.scrollTo(0,0);"
                'sPage &= cbTopicLoader.ClientID & ".Callback(page);"
                'sPage &= "};"
                'Page.ClientScript.RegisterClientScriptBlock(Page.GetType, "aftopicpg", sPage, True)
                BuildPager()
            End If
            
           
           

          

            
           
            
           
        End Sub
        Private Sub LinkControls(ByVal ctrls As ControlCollection)
            For Each ctrl As Control In ctrls
                If TypeOf (ctrl) Is ForumBase Then
                    DirectCast(ctrl, ForumBase).ModuleConfiguration = Me.ModuleConfiguration
                    DirectCast(ctrl, ForumBase).TopicId = TopicId
                End If
                If ctrl.Controls.Count > 0 Then
                    LinkControls(ctrl.Controls)
                End If
            Next
        End Sub
        Private Function ParseControls(ByVal sOutput As String) As String
            If Not Request.QueryString("dnnprintmode") Is Nothing Then
                sOutput = sOutput.Replace("[ADDREPLY]", String.Empty)
                sOutput = sOutput.Replace("[QUICKREPLY]", String.Empty)
                sOutput = sOutput.Replace("[TOPICSUBSCRIBE]", String.Empty)
                sOutput = sOutput.Replace("[AF:CONTROL:PRINTER]", String.Empty)
                sOutput = sOutput.Replace("[AF:CONTROL:EMAIL]", String.Empty)
                sOutput = sOutput.Replace("[PAGER1]", String.Empty)
                sOutput = sOutput.Replace("[PAGER2]", String.Empty)
                sOutput = sOutput.Replace("[SORTDROPDOWN]", String.Empty)
                sOutput = sOutput.Replace("[POSTRATINGBUTTON]", String.Empty)
                sOutput = sOutput.Replace("[JUMPTO]", String.Empty)
                sOutput = sOutput.Replace("[NEXTTOPIC]", String.Empty)
                sOutput = sOutput.Replace("[PREVTOPIC]", String.Empty)
                sOutput = sOutput.Replace("[AF:CONTROL:STATUS]", String.Empty)
                sOutput = sOutput.Replace("[ACTIONS:DELETE]", String.Empty)
                sOutput = sOutput.Replace("[ACTIONS:EDIT]", String.Empty)
                sOutput = sOutput.Replace("[ACTIONS:QUOTE]", String.Empty)
                sOutput = sOutput.Replace("[ACTIONS:REPLY]", String.Empty)
                sOutput = sOutput.Replace("[ACTIONS:ANSWER]", String.Empty)
                sOutput = sOutput.Replace("[ACTIONS:ALERT]", String.Empty)
                sOutput = sOutput.Replace("[RESX:SortPosts]:", String.Empty)
                sOutput = sOutput & "<img src=""~/desktopmodules/activeforums/images/spacer.gif"" width=""800"" height=""1"" runat=""server"" alt=""---"" />"
            End If
            If sOutput.Contains("[AF:CONTROL:ADDTHIS") Then
                Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request))
                sOutput = TemplateUtils.ParseSpecial(sOutput, SpecialTokenTypes.AddThis, strHost & Request.RawUrl, TopicSubject, bRead, MainSettings.AddThisAccount)
            End If
            sOutput = sOutput.Replace("[NOPAGING]", "<script type=""text/javascript"">afpagesize=" & Integer.MaxValue & ";</script>")
            sOutput = sOutput.Replace("[NOTOOLBAR]", String.Empty)
            If bSubscribe = True Then
                Dim subControl As New Controls.ToggleSubscribe(1, ForumId, TopicId)
                subControl.Checked = IsSubscribedTopic
                subControl.Text = "[RESX:TopicSubscribe:" & IsSubscribedTopic.ToString.ToUpper & "]"
                sOutput = sOutput.Replace("[TOPICSUBSCRIBE]", subControl.Render())
            Else
                sOutput = sOutput.Replace("[TOPICSUBSCRIBE]", String.Empty)
            End If
            Dim tc As New TokensController
            Dim topicActions As String = tc.TokenGet("topic", "[AF:CONTROL:TOPICACTIONS]")
            Dim postActions As String = tc.TokenGet("topic", "[AF:CONTROL:POSTACTIONS]")
            If sOutput.Contains("[AF:CONTROL:TOPICACTIONS]") Then
                UseListActions = True
                sOutput = sOutput.Replace("[AF:CONTROL:TOPICACTIONS]", topicActions)
                sOutput = sOutput.Replace("[AF:CONTROL:POSTACTIONS]", postActions)
            End If
            

            If sOutput.IndexOf("[BANNER") > 0 Then
                Dim bannerCount As Integer = 1
                sOutput = "<%@ Register TagPrefix=""dnn"" TagName=""BANNER"" Src=""~/Admin/Skins/Banner.ascx"" %>" & sOutput
                sOutput = sOutput.Replace("[BANNER]", "<dnn:BANNER runat=""server"" id=""dnnBANNER" & bannerCount & """ BannerTypeId=""-1"" GroupName=""FORUMS"" EnableViewState=""False"" />")
                Dim pattern As String = "(\[BANNER:(.+?)\])"
                Dim regExp As New Text.RegularExpressions.Regex(pattern)
                Dim matches As Text.RegularExpressions.MatchCollection
                matches = regExp.Matches(sOutput)
                Dim sBanner As String = "<dnn:BANNER runat=""server"" id=""dnnBANNER{0}"" BannerTypeId=""-1"" GroupName=""{1}"" EnableViewState=""False"" />"
                For Each match As Text.RegularExpressions.Match In matches
                    Dim sReplace As String
                    bannerCount += 1
                    sReplace = String.Format(sBanner, bannerCount, match.Groups(2).Value)
                    sOutput = regExp.Replace(sOutput, sReplace, 1)
                Next match
            End If
            If bLocked = True Then
                sOutput = sOutput.Replace("[ADDREPLY]", "<span class=""afnormal"">[RESX:TopicLocked]</span>")
                sOutput = sOutput.Replace("[QUICKREPLY]", String.Empty)
            Else
                'TODO: Check for owner
                If bReply Then
                    Dim Params() As String = {ParamKeys.ViewType & "=post", ParamKeys.TopicId & "=" & TopicId, ParamKeys.ForumId & "=" & ForumId}
                    If SocialGroupId > 0 Then
                        Params = Utilities.AddParams("GroupId=" & SocialGroupId, Params)
                    End If
                    sOutput = sOutput.Replace("[ADDREPLY]", "<a href=""" & Utilities.NavigateUrl(TabId, "", Params) & """ class=""dnnPrimaryAction"">[RESX:AddReply]</a>")
                    sOutput = sOutput.Replace("[QUICKREPLY]", "<asp:placeholder id=""plhQuickReply"" runat=""server"" />")
                Else
                    sOutput = sOutput.Replace("[ADDREPLY]", "<span class=""afnormal"">[RESX:NotAuthorizedReply]</span>")
                    sOutput = sOutput.Replace("[QUICKREPLY]", String.Empty)
                End If
                End If
            If sOutput.Contains("[PARENTFORUMLINK]") Then
                If ForumInfo.ParentForumId > 0 Then
                    If MainSettings.UseShortUrls Then
                        sOutput = sOutput.Replace("[PARENTFORUMLINK]", "<a href=""" & Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumInfo.ParentForumId}) & """>" & ForumInfo.ParentForumName & "</a>")
                    Else
                        sOutput = sOutput.Replace("[PARENTFORUMLINK]", "<a href=""" & Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & ForumInfo.ParentForumId}) & """>" & ForumInfo.ParentForumName & "</a>")
                    End If

                ElseIf ForumInfo.ForumGroupId > 0 Then
                    sOutput = sOutput.Replace("[PARENTFORUMLINK]", "<a href=""" & Utilities.NavigateUrl(TabId) & """>" & ForumInfo.GroupName & "</a>")
                End If
            End If
            If String.IsNullOrEmpty(ForumInfo.ParentForumName) Then
                sOutput = sOutput.Replace("[PARENTFORUMNAME]", ForumInfo.ParentForumName)
            End If
            sOutput = sOutput.Replace("[FORUMMAINLINK]", "<a href=""" & Utilities.NavigateUrl(TabId) & """>[RESX:ForumMain]</a>")
            sOutput = sOutput.Replace("[FORUMGROUPLINK]", "<a href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.GroupId & "=" & ForumGroupId) & """>" & GroupName & "</a>")
            If MainSettings.UseShortUrls Then
                sOutput = sOutput.Replace("[FORUMLINK]", "<a href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.ForumId & "=" & ForumId) & """>" & ForumName & "</a>")
            Else
                sOutput = sOutput.Replace("[FORUMLINK]", "<a href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.ViewType & "=" & Views.Topics & "&" & ParamKeys.ForumId & "=" & ForumId) & """>" & ForumName & "</a>")
            End If

            sOutput = sOutput.Replace("[FORUMID]", ForumId.ToString)
            sOutput = sOutput.Replace("[FORUMNAME]", ForumName)
            sOutput = sOutput.Replace("[GROUPNAME]", GroupName)
            Dim sURL As String = "<a rel=""nofollow"" href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & TopicId, "mid=" & ModuleId.ToString, "dnnprintmode=true") & "?skinsrc=" & HttpUtility.UrlEncode("[G]" & DotNetNuke.UI.Skins.SkinInfo.RootSkin & "/" & DotNetNuke.Common.glbHostSkinFolder & "/" & "No Skin") & "&amp;containersrc=" & HttpUtility.UrlEncode("[G]" & DotNetNuke.UI.Skins.SkinInfo.RootContainer & "/" & DotNetNuke.Common.glbHostSkinFolder & "/" & "No Container") & """ target=""_blank"">"
            sURL &= "<img src=""" & MyThemePath & "/images/print16.png"" border=""0"" alt=""[RESX:PrinterFriendly]"" /></a>"
            sOutput = sOutput.Replace("[AF:CONTROL:PRINTER]", sURL)
            If Request.IsAuthenticated Then
                sURL = Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=sendto", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId})
                sOutput = sOutput.Replace("[AF:CONTROL:EMAIL]", "<a href=""" & sURL & """ rel=""nofollow""><img src=""" & MyThemePath & "/images/email16.png"" border=""0"" alt=""[RESX:EmailThis]"" /></a>")
            Else
                sOutput = sOutput.Replace("[AF:CONTROL:EMAIL]", String.Empty)
            End If
            If bAllowRSS Then
                Dim Url As String
                Url = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/DesktopModules/ActiveForums/feeds.aspx?portalid=" & PortalId & "&forumid=" & ForumId & "&tabid=" & TabId & "&moduleid=" & ModuleId
                sOutput = sOutput.Replace("[RSSLINK]", "<a href=""" & Url & """><img src=""~/DesktopModules/ActiveForums/themes/" & MyTheme & "/images/rss.png"" runat=server border=""0"" alt=""[RESX:RSS]"" /></a>")
            Else
                sOutput = sOutput.Replace("[RSSLINK]", String.Empty)
            End If
            TopicSubject = Replace(TopicSubject, "[", "&#91")
            TopicSubject = Replace(TopicSubject, "]", "&#93")
            sOutput = sOutput.Replace("[SUBJECT]", Utilities.StripHTMLTag(TopicSubject))
            sOutput = sOutput.Replace("[REPLYCOUNT]", ReplyCount.ToString)
            sOutput = sOutput.Replace("[AF:LABEL:ReplyCount]", ReplyCount.ToString)
            sOutput = sOutput.Replace("[VIEWCOUNT]", ViewCount.ToString)
            sOutput = sOutput.Replace("[AF:LABEL:LastPostDate]", LastPostDate)
            sOutput = sOutput.Replace("[AF:LABEL:LastPostAuthor]", UserProfiles.GetDisplayName(ModuleId, MainSettings.MemberListMode, bModApprove, LastPostAuthor.AuthorId, MainSettings.UserNameDisplay, LastPostAuthor))
            sOutput = sOutput.Replace("[AF:LABEL:TopicAuthor]", UserProfiles.GetDisplayName(ModuleId, TopicAuthorId, MainSettings.MemberListMode, TopicAuthorDisplayName, String.Empty, String.Empty, TopicAuthorDisplayName))
            sOutput = sOutput.Replace("[AF:LABEL:TopicDateCreated]", TopicDateCreated)
            If PageSize = Integer.MaxValue Then
                sOutput = sOutput.Replace("[PAGER1]", String.Empty)
                sOutput = sOutput.Replace("[PAGER2]", String.Empty)
            Else
                sOutput = sOutput.Replace("[PAGER1]", "<am:pagernav id=""Pager1"" runat=""server"" EnableViewState=""False"" />")
                sOutput = sOutput.Replace("[PAGER2]", "<am:pagernav id=""Pager2"" runat=""server"" EnableViewState=""False"" />")
            End If

            sOutput = sOutput.Replace("[SORTDROPDOWN]", "<asp:placeholder id=""plhTopicSort"" runat=""server"" />")
            Dim rateControl As New Ratings(TopicId, True, TopicRating)
            sOutput = sOutput.Replace("[POSTRATINGBUTTON]", rateControl.Render())
            sOutput = sOutput.Replace("[JUMPTO]", "<asp:placeholder id=""plhQuickJump"" runat=""server"" />")
            If NextTopic = 0 Then
                sOutput = sOutput.Replace("[NEXTTOPIC]", String.Empty)
            Else
                If MainSettings.UseShortUrls Then
                    sOutput = sOutput.Replace("[NEXTTOPIC]", "<a href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.TopicId & "=" & NextTopic) & """ rel=""nofollow""><span>[RESX:NextTopic]</span><img src=""~/DesktopModules/ActiveForums/themes/" & MyTheme & "/images/arrow_right_blue.gif"" runat=server style=""vertical-align:middle;"" border=""0"" alt=""[RESX:NextTopic]"" /></a>")
                Else
                    sOutput = sOutput.Replace("[NEXTTOPIC]", "<a href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.ForumId & "=" & ForumId & "&" & ParamKeys.TopicId & "=" & NextTopic & "&" & ParamKeys.ViewType & "=" & Views.Topic) & """ rel=""nofollow""><span>[RESX:NextTopic]</span><img src=""~/DesktopModules/ActiveForums/themes/" & MyTheme & "/images/arrow_right_blue.gif"" runat=server style=""vertical-align:middle;"" border=""0"" alt=""[RESX:NextTopic]"" /></a>")
                End If

            End If
            If PrevTopic = 0 Then
                sOutput = sOutput.Replace("[PREVTOPIC]", String.Empty)
            Else
                If MainSettings.UseShortUrls Then
                    sOutput = sOutput.Replace("[PREVTOPIC]", "<a href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.TopicId & "=" & PrevTopic) & """ rel=""nofollow""><img src=""~/DesktopModules/ActiveForums/themes/" & MyTheme & "/images/arrow_left_blue.gif"" runat=server style=""vertical-align:middle;"" border=""0"" alt=""[RESX:PrevTopic]"" /><span>[RESX:PrevTopic]</span></a>")
                Else
                    sOutput = sOutput.Replace("[PREVTOPIC]", "<a href=""" & Utilities.NavigateUrl(TabId, "", ParamKeys.ForumId & "=" & ForumId & "&" & ParamKeys.TopicId & "=" & PrevTopic & "&" & ParamKeys.ViewType & "=" & Views.Topic) & """ rel=""nofollow""><img src=""~/DesktopModules/ActiveForums/themes/" & MyTheme & "/images/arrow_left_blue.gif"" runat=server style=""vertical-align:middle;"" border=""0"" alt=""[RESX:PrevTopic]"" /><span>[RESX:PrevTopic]</span></a>")
                End If

            End If


            If ((bRead And TopicAuthorId = Me.UserId) Or bModEdit) And StatusId >= 0 Then
                sOutput = sOutput.Replace("[AF:CONTROL:STATUS]", "<asp:placeholder id=""plhStatus"" runat=""server"" />")
                sOutput = sOutput.Replace("[AF:CONTROL:STATUSICON]", "<img alt=""[RESX:PostStatus" & StatusId.ToString & "]"" src=""" & MyThemePath & "/images/status" & StatusId.ToString & ".png"" />")
            ElseIf StatusId >= 0 Then
                sOutput = sOutput.Replace("[AF:CONTROL:STATUS]", String.Empty)
                sOutput = sOutput.Replace("[AF:CONTROL:STATUSICON]", "<img alt=""[RESX:PostStatus" & StatusId.ToString & "]"" src=""" & MyThemePath & "/images/status" & StatusId.ToString & ".png"" />")
            Else
                sOutput = sOutput.Replace("[AF:CONTROL:STATUS]", String.Empty)
                sOutput = sOutput.Replace("[AF:CONTROL:STATUSICON]", String.Empty)
            End If

            If TopicType = TopicTypes.Poll Then
                sOutput = sOutput.Replace("[AF:CONTROL:POLL]", "<asp:placeholder id=""plhPoll"" runat=""server"" />")
            Else
                sOutput = sOutput.Replace("[AF:CONTROL:POLL]", String.Empty)
            End If
            Return sOutput
        End Function
        Private Function ParseTopic(ByVal sOutput As String) As String
            Dim sTopicTemplate As String = TemplateUtils.GetTemplateSection(sOutput, "[TOPIC]", "[/TOPIC]")
            Dim sReplyTemplate As String = TemplateUtils.GetTemplateSection(sOutput, "[REPLIES]", "[/REPLIES]")
            Dim sTemp As String = String.Empty
            Dim i As Integer = 0
            If dtTopic.Rows.Count > 0 Then
                Dim dr As DataRow = Nothing
                For Each dr In dtTopic.Rows
                    Dim ReplyId As Integer = CInt(dr("ReplyId"))

                    If ReplyId = 0 Then
                        sTopicTemplate = ParseContent(dr, sTopicTemplate, i)
                        'sOutput = TemplateUtils.ReplaceSubSection(sOutput, sTopicTemplate, "[TOPIC]", "[/TOPIC]")
                    Else
                        sTemp &= ParseContent(dr, sReplyTemplate, i)
                    End If
                    i += 1
                Next
                If DefaultSort = "ASC" Then
                    sOutput = TemplateUtils.ReplaceSubSection(sOutput, sTemp, "[REPLIES]", "[/REPLIES]")
                    sOutput = TemplateUtils.ReplaceSubSection(sOutput, sTopicTemplate, "[TOPIC]", "[/TOPIC]")
                Else
                    sOutput = TemplateUtils.ReplaceSubSection(sOutput, sTemp & sTopicTemplate, "[REPLIES]", "[/REPLIES]")
                    sOutput = TemplateUtils.ReplaceSubSection(sOutput, String.Empty, "[TOPIC]", "[/TOPIC]")
                End If
                If sTopicTemplate.Contains("[BODY]") Then
                    sOutput = sOutput.Replace(sTopicTemplate, String.Empty)
                End If

            End If

            Return sOutput
        End Function
        Private Function ParseContent(ByVal dr As DataRow, ByVal tempate As String, ByVal rowcount As Integer) As String
            Dim sOutput As String = tempate
            If rowcount Mod 2 = 0 Then
                sOutput = sOutput.Replace("[POSTINFOCSS]", "afpostinfo1")
                sOutput = sOutput.Replace("[POSTTOPICCSS]", "afpostreply1")
                sOutput = sOutput.Replace("[POSTREPLYCSS]", "afpostreply1")
            Else
                sOutput = sOutput.Replace("[POSTTOPICCSS]", "afpostreply2")
                sOutput = sOutput.Replace("[POSTINFOCSS]", "afpostinfo2")
                sOutput = sOutput.Replace("[POSTREPLYCSS]", "afpostreply2")
            End If
            Dim ReplyId As Integer = CInt(dr("ReplyId"))
            Dim TopicId As Integer = CInt(dr("TopicId"))
            Dim ContentId As Integer = CInt(dr("ContentId"))
            Dim PostId As Integer = 0
            Dim DateCreated As Date = CDate(dr("DateCreated"))
            Dim DateUpdated As Date = CDate(dr("DateUpdated"))
            Dim AuthorId As Integer = CInt(dr("AuthorId"))
            Dim Username As String = CStr(dr("Username"))
            Dim FirstName As String = CStr(dr("FirstName"))
            Dim LastName As String = CStr(dr("LastName"))
            Dim DisplayName As String = CStr(dr("DisplayName"))
            Dim UserTopicCount As Integer = CInt(dr("TopicCount"))
            Dim UserReplyCount As Integer = CInt(dr("ReplyCount"))
            Dim UserCaption As String = CStr(dr("UserCaption"))
            Dim Body As String = CStr(dr("Body"))
            Dim Subject As String = CStr(dr("Subject"))
            Dim Tags As String = dr("Tags").ToString
            Dim Signature As String = CStr(dr("Signature"))
            Dim IPAddress As String = CStr(dr("IPAddress"))
            Dim Avatar As String = CStr(dr("Avatar"))
            Dim AvatarType As Integer = CInt(dr("AvatarType"))
            Dim Yahoo As String = CStr(dr("Yahoo"))
            Dim MSN As String = CStr(dr("MSN"))
            Dim ICQ As String = CStr(dr("ICQ"))
            Dim AOL As String = CStr(dr("AOL"))
            Dim Occupation As String = CStr(dr("Occupation"))
            Dim Location As String = CStr(dr("Location"))
            Dim Interests As String = CStr(dr("Interests"))
            Dim WebSite As String = CStr(dr("WebSite"))
            Dim MemberSince As Date = CDate(dr("MemberSince"))
            Dim AvatarDisabled As Boolean = CBool(dr("AvatarDisabled"))
            Dim UserRoles As String = CStr(dr("UserRoles"))
            Dim IsUserOnline As Boolean = CBool(dr("IsUserOnline"))
            Dim ReplyStatusId As Integer = CInt(dr("StatusId"))
            Dim TotalPoints As Integer = 0
            Dim AnswerCount As Integer = CInt(dr("AnswerCount"))
            Dim RewardPoints As Integer = CInt(dr("RewardPoints"))
            Dim DateLastActivity As Date = CDate(dr("DateLastActivity"))
            Dim SignatureDisabled As Boolean = CBool(dr("SignatureDisabled"))
            'TODO:  Need to finish adding points
            Dim PostCount As Integer = UserTopicCount + UserReplyCount
            If EnablePoints Then
                TotalPoints = CInt(dr("UserTotalPoints"))
            End If
            Dim up As New User
            With up
                .UserId = AuthorId
                .UserName = Username
                .FirstName = FirstName.Replace("&amp;#", "&#")
                .LastName = LastName.Replace("&amp;#", "&#")
                .DisplayName = DisplayName.Replace("&amp;#", "&#")

                With .Profile
                    .UserCaption = UserCaption
                    .Signature = Signature
                    .Avatar = Avatar
                    .AvatarType = CType(AvatarType, AvatarTypes)
                    .Yahoo = Yahoo
                    .MSN = MSN
                    .ICQ = ICQ
                    .AOL = AOL
                    .Occupation = Occupation
                    .Location = Location
                    .Interests = Interests
                    .WebSite = WebSite
                    .DateCreated = MemberSince
                    .AvatarDisabled = AvatarDisabled
                    .Roles = UserRoles
                    .ReplyCount = UserReplyCount
                    .TopicCount = UserTopicCount
                    .AnswerCount = AnswerCount
                    .RewardPoints = RewardPoints
                    .DateLastActivity = DateLastActivity
                    .PrefBlockAvatars = UserPrefHideAvatars
                    .PrefBlockSignatures = UserPrefHideSigs
                    .IsUserOnline = IsUserOnline
                    .SignatureDisabled = SignatureDisabled
                End With



            End With
            If ReplyId = 0 Then
                sOutput = sOutput.Replace("[POSTID]", TopicId.ToString)
                PostId = TopicId
                TopicDescription = Utilities.StripHTMLTag(Body).Trim
                TopicDescription = TopicDescription.Replace(vbCrLf, String.Empty)
                If TopicDescription.Length > 255 Then
                    TopicDescription = TopicDescription.Substring(0, 255)
                End If


            Else
                sOutput = sOutput.Replace("[POSTID]", ReplyId.ToString)
                PostId = ReplyId
            End If
            sOutput = sOutput.Replace("[FORUMID]", ForumId.ToString)
            sOutput = sOutput.Replace("[REPLYID]", ReplyId.ToString)
            sOutput = sOutput.Replace("[TOPICID]", TopicId.ToString)
            sOutput = sOutput.Replace("[POSTDATE]", GetDate(DateCreated))
            sOutput = sOutput.Replace("[DATECREATED]", GetDate(DateCreated))
            If Tags = String.Empty Then
                sOutput = TemplateUtils.ReplaceSubSection(sOutput, String.Empty, "[AF:CONTROL:TAGS]", "[/AF:CONTROL:TAGS]")
            Else
                sOutput = sOutput.Replace("[AF:CONTROL:TAGS]", String.Empty)
                sOutput = sOutput.Replace("[/AF:CONTROL:TAGS]", String.Empty)
                Dim tag As String = String.Empty
                Dim tagList As String = String.Empty
                Dim i As Integer = 0
                For Each tag In Tags.Split(CChar(","))
                    tagList &= "<a href=""" & Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=search", ParamKeys.Tags & "=" & HttpUtility.UrlEncode(tag)}) & """>" & tag & "</a>"
                    i += 1
                    If i <= Tags.Split(CChar(",")).GetUpperBound(0) Then
                        tagList &= ", "
                    End If

                Next
                sOutput = sOutput.Replace("[AF:LABEL:TAGS]", tagList)
            End If
            'Perform Profile Related replacements
            sOutput = TemplateUtils.ParseProfileTemplate(sOutput, up, PortalId, ModuleId, ImagePath, CurrentUserType, True, UserPrefHideAvatars, UserPrefHideSigs, IPAddress, TimeZoneOffset)

            If bModDelete Or ((bDelete And AuthorId = UserId And bLocked = False) And ((ReplyId = 0 And ReplyCount = 0) Or ReplyId > 0)) Then
                If UseListActions Then
                    sOutput = sOutput.Replace("[ACTIONS:DELETE]", "<li class=""af-delete"" onclick=""amaf_postDel(" & TopicId & "," & ReplyId & ");"" title=""[RESX:Delete]""><em></em>[RESX:Delete]</li>")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:DELETE]", "<a href=""javascript:void(0);"" class=""af-actions af-delete"" onclick=""amaf_postDel(" & TopicId & "," & ReplyId & ");"" title=""[RESX:Delete]""><em></em>[RESX:Delete]</a>")
                End If

            Else
                sOutput = sOutput.Replace("[ACTIONS:DELETE]", String.Empty)
            End If
            If bModEdit Or (bEdit And AuthorId = UserId And (EditInterval = 0 Or DateDiff(DateInterval.Minute, DateCreated, Now()) < EditInterval)) Then
                Dim sAction As String = "re"
                If ReplyId = 0 Then
                    sAction = "te"
                End If
                Dim EditParams() As String = {ParamKeys.ViewType & "=post", "action=" & sAction, ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, "postid=" & PostId}
                If UseListActions Then
                    sOutput = sOutput.Replace("[ACTIONS:EDIT]", "<li class=""af-edit"" onclick=""window.location.href='" & Utilities.NavigateUrl(TabId, "", EditParams) & "';"" title=""[RESX:Edit]""><em></em>[RESX:Edit]</li>")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:EDIT]", "<a class=""af-actions af-edit"" href=""" & Utilities.NavigateUrl(TabId, "", EditParams) & """ title=""[RESX:Edit]""><em></em>[RESX:Edit]</a>")
                End If

            Else
                sOutput = sOutput.Replace("[ACTIONS:EDIT]", String.Empty)
            End If
            If bLocked = False Then
                If bReply Or bReply And AuthorId = UserId Then
                    Dim QuoteParams() As String = {ParamKeys.ViewType & "=post", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.QuoteId & "=" & PostId}
                    Dim ReplyParams() As String = {ParamKeys.ViewType & "=post", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ReplyId & "=" & PostId}
                    If UseListActions Then
                        sOutput = sOutput.Replace("[ACTIONS:QUOTE]", "<li class=""af-quote"" onclick=""window.location.href='" & Utilities.NavigateUrl(TabId, "", QuoteParams) & "';"" title=""[RESX:Quote]""><em></em>[RESX:Quote]</li>")
                        sOutput = sOutput.Replace("[ACTIONS:REPLY]", "<li class=""af-reply"" onclick=""window.location.href='" & Utilities.NavigateUrl(TabId, "", ReplyParams) & "';"" title=""[RESX:Reply]""><em></em>[RESX:Reply]</li>")
                    Else
                        sOutput = sOutput.Replace("[ACTIONS:QUOTE]", "<a class=""af-actions af-quote"" href=""" & Utilities.NavigateUrl(TabId, "", QuoteParams) & """ title=""[RESX:Quote]""><em></em>[RESX:Quote]</a>")
                        sOutput = sOutput.Replace("[ACTIONS:REPLY]", "<a class=""af-actions af-reply"" href=""" & Utilities.NavigateUrl(TabId, "", ReplyParams) & """ title=""[RESX:Reply]""><em></em>[RESX:Reply]</a>")
                    End If



                Else
                    sOutput = sOutput.Replace("[ACTIONS:QUOTE]", String.Empty)
                    sOutput = sOutput.Replace("[ACTIONS:REPLY]", String.Empty)
                End If
            Else
                sOutput = sOutput.Replace("[ACTIONS:QUOTE]", String.Empty)
                sOutput = sOutput.Replace("[ACTIONS:REPLY]", String.Empty)
            End If

            If StatusId <= 0 Or (StatusId = 3 And ReplyStatusId = 0) Then
                sOutput = sOutput.Replace("[ACTIONS:ANSWER]", String.Empty)
            ElseIf ReplyStatusId = 1 Then
                'Answered
                If UseListActions Then
                    sOutput = sOutput.Replace("[ACTIONS:ANSWER]", "<li class=""af-answered"" title=""[RESX:Status:Answer]""><em></em>[RESX:Status:Answer]</li>")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:ANSWER]", "<span class=""af-actions af-answered"" title=""[RESX:Status:Answer]""><em></em>[RESX:Status:Answer]</span>")
                End If

            Else
                'Not Answered
                If (Me.UserId = TopicAuthorId And Not bLocked) Or bModEdit Then
                    'Can mark answer
                    Dim sLink As String = String.Empty
                    If UseListActions Then
                        sLink = "<li class=""af-markanswer"" onclick=""amaf_markAnswer(" & TopicId.ToString & "," & ReplyId.ToString & ");"" title=""[RESX:Status:SelectAnswer]""><em></em>[RESX:Status:SelectAnswer]</li>"
                    Else
                        sLink = "<a class=""af-actions af-markanswer"" href=""#"" onclick=""amaf_markAnswer(" & TopicId.ToString & "," & ReplyId.ToString & "); return false;"" title=""[RESX:Status:SelectAnswer]""><em></em>[RESX:Status:SelectAnswer]</a>"
                    End If

                    sOutput = sOutput.Replace("[ACTIONS:ANSWER]", sLink)
                Else
                    'Display Nothing
                    sOutput = sOutput.Replace("[ACTIONS:ANSWER]", String.Empty)

                End If
            End If

            If bModEdit Then
                If DateCreated = DateUpdated Or DateUpdated = Date.MinValue Or DateUpdated = Utilities.NullDate Then
                    sOutput = sOutput.Replace("[MODEDITDATE]", String.Empty)
                Else
                    sOutput = sOutput.Replace("[MODEDITDATE]", Utilities.GetDate(DateUpdated, ModuleId, TimeZoneOffset))
                End If
            Else
                sOutput = sOutput.Replace("[MODEDITDATE]", String.Empty)
            End If
            If InStr(sOutput, "[POLLRESULTS]") > 0 Then
                If TopicType = 1 Then
                    Dim Polls As New Polls
                    sOutput = sOutput.Replace("[POLLRESULTS]", Polls.PollResults(TopicId, ImagePath))
                Else
                    sOutput = sOutput.Replace("[POLLRESULTS]", String.Empty)
                End If
            End If

            If DateUpdated = DateCreated Or DateUpdated = Date.MinValue Or DateUpdated = Utilities.NullDate Then
                sOutput = sOutput.Replace("[EDITDATE]", String.Empty)
            Else
                sOutput = sOutput.Replace("[EDITDATE]", Utilities.GetDate(DateUpdated, ModuleId, TimeZoneOffset))
            End If


            Dim AlertParams() As String = {ParamKeys.ViewType & "=modreport", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ReplyId & "=" & PostId}
            If Request.IsAuthenticated Then
                If UseListActions Then
                    sOutput = sOutput.Replace("[ACTIONS:ALERT]", "<li class=""af-alert"" onclick=""window.location.href='" & Utilities.NavigateUrl(TabId, "", AlertParams) & "';"" title=""[RESX:Alert]""><em></em>[RESX:Alert]</li>")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:ALERT]", "<a class=""af-actions af-alert"" href=""" & Utilities.NavigateUrl(TabId, "", AlertParams) & """ title=""[RESX:Alert]""><em></em>[RESX:Alert]</a>")
                End If

            Else
                sOutput = sOutput.Replace("[ACTIONS:ALERT]", String.Empty)
            End If
            If String.IsNullOrEmpty(Body) Then
                Body = " <br />"
            End If
            Dim sBody As String = Utilities.ManageImagePath(Body)



            sBody = Replace(sBody, "[", "&#91;")
            sBody = Replace(sBody, "]", "&#93;")
            If sBody.ToUpper.Contains("&#91;CODE&#93;") Then
                sBody = Regex.Replace(sBody, "(&#91;CODE&#93;)", "[CODE]", RegexOptions.IgnoreCase)
                sBody = Regex.Replace(sBody, "(&#91;\/CODE&#93;)", "[/CODE]", RegexOptions.IgnoreCase)

            End If
            'sBody = sBody.Replace("&lt;CODE&gt;", "<CODE>")
            If Regex.IsMatch(sBody, "\[CODE([^>]*)\]", RegexOptions.IgnoreCase) Then
                Dim objCode As New CodeParser
                sBody = CodeParser.ParseCode(Utilities.HTMLDecode(sBody))
            End If
            sBody = Utilities.StripExecCode(sBody)
            If MainSettings.AutoLinkEnabled Then
                sBody = Utilities.AutoLinks(sBody, Request.Url.Host)
            End If

            If sBody.Contains("<%@") Then
                sBody = sBody.Replace("<%@ ", "&lt;&#37;@ ")
            End If

            'sBody = Replace(sBody, " #", " &#35;")
            'sBody = Replace(sBody, "-#", "-&#35;")
            'sBody = Replace(sBody, "<%", "&lt;&#37;")
            'sBody = Replace(sBody, "%>", "&#37;&gt;")
            If Body.ToLowerInvariant.Contains("runat") Then
                sBody = Regex.Replace(sBody, "runat", "&#114;&#117;nat", RegexOptions.IgnoreCase)
            End If
            'Dim sysEx As New System.Web.RegularExpressions.RunatServerRegex
            'sBody = sysEx.Replace(sBody, "&#114;&#117;nat")
            ''sBody = Replace(sBody, "runat", "&#114;&#117;nat")
            'sBody = Replace(sBody, "<!--", "&lt;&#33;&#45;&#45;")
            'sBody = Replace(sBody, "-->", "&#45;&#45;&gt;")

            sOutput = sOutput.Replace("[BODY]", sBody)
            sOutput = sOutput.Replace("[SUBJECT]", Subject)
            Dim sAttach As String = String.Empty
            If dtAttach.Rows.Count > 0 Then
                sAttach = GetAttachments(ContentId, bAttach, PortalId, ModuleId)
            End If
            sOutput = sOutput.Replace("[ATTACHMENTS]", sAttach)

            '&#91;IMAGE:38&#93;
            If sOutput.Contains("&#91;IMAGE:") Then
                Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/"
                Dim pattern As String = "(&#91;IMAGE:(.+?)&#93;)"
                Dim regExp As New Regex(pattern)
                Dim matches As MatchCollection
                matches = regExp.Matches(sOutput)
                For Each match As Match In matches
                    Dim sImage As String = ""
                    sImage = "<img src=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & match.Groups(2).Value & """ border=""0"" class=""afimg"" />"
                    sOutput = sOutput.Replace(match.Value, sImage)
                Next match
            End If
            If sOutput.Contains("&#91;THUMBNAIL:") Then
                Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/"
                Dim pattern As String = "(&#91;THUMBNAIL:(.+?)&#93;)"
                Dim regExp As New Regex(pattern)
                Dim matches As MatchCollection
                matches = regExp.Matches(sOutput)
                For Each match As Match In matches
                    Dim sImage As String = ""
                    Dim thumbId As String = match.Groups(2).Value.Split(CChar(":"))(0)
                    Dim parentId As String = match.Groups(2).Value.Split(CChar(":"))(1)
                    sImage = "<a href=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & parentId & """ target=""_blank""><img src=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & thumbId & """ border=""0"" class=""afimg"" /></a>"
                    sOutput = sOutput.Replace(match.Value, sImage)
                Next match
            End If


            Return sOutput
        End Function
        Private Function GetAttachments(ByVal ContentId As Integer, ByVal AllowAttach As Boolean, ByVal PortalID As Integer, ByVal ModuleID As Integer) As String
            AllowAttach = True
            Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/"
            If Request.IsSecureConnection Then
                strHost = Replace(strHost, "http://", "https://")
            End If
            'TODO: Add option for folder storage
            Dim sb As New Text.StringBuilder(1024)
            If AllowAttach = True Then
                Dim vpath As String
                vpath = PortalSettings.HomeDirectory & "activeforums_Attach/"
                Dim fpath As String
                fpath = Server.MapPath(PortalSettings.HomeDirectory & "activeforums_Attach/")
                Dim dr As DataRow = Nothing
                dtAttach.DefaultView.RowFilter = "ContentId = " & ContentId
                sb.Append("<br />")
                For Each dr In dtAttach.DefaultView.ToTable.Rows
                    Dim tmpPath As String
                    Dim attachId As Integer = CInt(dr("AttachId"))
                    Dim Filename As String = dr("Filename").ToString
                    Dim contentType As String = dr("ContentType").ToString
                    Dim fileURL As String = String.Empty
                    If Not String.IsNullOrEmpty(dr("FileURL").ToString()) Then
                        fileURL = Page.ResolveUrl(dr("FileURL").ToString())
                    End If
                    If dr.IsNull("FileData") And String.IsNullOrEmpty(fileURL) Then
                        tmpPath = fpath & dr("Filename").ToString
                        If Not System.IO.File.Exists(tmpPath) Then
                            tmpPath = tmpPath.Replace("activeforums_Attach", "ntforums_attach")
                        End If
                        Dim strExt As String = System.IO.Path.GetExtension(tmpPath)
                        Dim sPath As String = strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalID & "&moduleid=" & ModuleID & "&attachid=" & attachId
                        'sb.Append("<a href=""" & vpath & Filename & """ target=""_blank"">")
                        sb.Append("<a href=""" & sPath & """ target=""_blank"">")
                        sb.Append("<img src=""" & strHost & "DesktopModules/ActiveForums/images/attach.gif"" border=""0"" align=""absmiddle"" />" & Filename & "</a><br />")
                    ElseIf Not String.IsNullOrEmpty(fileURL) Then
                        'If contentType.Contains("jpg") Or contentType.Contains("jpeg") Or contentType.Contains("png") Or contentType.Contains("gif") Or contentType.Contains("bmp") Then
                        '    sb.Append("<img src=""" & fileURL & """ />")
                        'Else
                        sb.Append("<a href=""" & fileURL & """ target=""_blank"">" & Filename & "</a>")
                        'End If

                    Else
                        Dim strExt As String = System.IO.Path.GetExtension(Filename)
                        sb.Append("<span class=""afattachlink""><a href=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalID & "&moduleid=" & ModuleID & "&attachid=" & attachId & """ target=""_blank""><img src=""" & strHost & "DesktopModules/ActiveForums/images/attach.gif"" border=""0"" align=""absmiddle"" /><span>" & Filename & "</span></a></span><br />")
                    End If
                Next
                sb.Append("<br />")

                Return sb.ToString
            Else
                Return String.Empty
            End If
        End Function
        Private Sub BuildPager()
            Dim obj As Object = Nothing
            Dim Pager1 As DotNetNuke.Modules.ActiveForums.Controls.PagerNav = Nothing
            obj = Me.FindControl("Pager1")
            If Not obj Is Nothing Then
                Pager1 = CType(Me.FindControl("Pager1"), DotNetNuke.Modules.ActiveForums.Controls.PagerNav)
            End If
            obj = Nothing
            Dim Pager2 As DotNetNuke.Modules.ActiveForums.Controls.PagerNav = Nothing
            obj = Me.FindControl("Pager2")
            If Not obj Is Nothing Then
                Pager2 = CType(obj, DotNetNuke.Modules.ActiveForums.Controls.PagerNav)
            End If
            If Pager1 Is Nothing And Pager2 Is Nothing Then
                Exit Sub
            End If

            Dim intPages As Integer
            intPages = CType(System.Math.Ceiling(RowCount / PageSize), Integer)
            Pager1.PageCount = intPages
            Pager1.CurrentPage = PageId
            Pager1.TabID = CType(Request.Params("TabId"), Integer)
            Pager1.ForumID = ForumId
            Pager1.UseShortUrls = MainSettings.UseShortUrls
            Pager1.PageText = Utilities.GetSharedResource("[RESX:Page]")
            Pager1.OfText = Utilities.GetSharedResource("[RESX:PageOf]")
            Pager1.View = Views.Topic
            Pager1.TopicId = TopicId
            'Pager1.ClientScript = "afPageTopic({0});"
            'If UseAjax Then
            'Pager1.PageMode = PagerNav.Mode.CallBack
            'Else
            Pager1.PageMode = PagerNav.Mode.Links
            'End If
            If Not TopicURL.Contains(ForumInfo.PrefixURL) Then
                TopicURL = "/" & ForumInfo.PrefixURL & "/" & TopicURL
            End If
            If MainSettings.URLRewriteEnabled Then
                If Not String.IsNullOrEmpty(TopicURL) Then
                    If Not String.IsNullOrEmpty(MainSettings.PrefixURLBase) Then
                        Pager1.BaseURL = "/" & MainSettings.PrefixURLBase
                    End If
                    If Not ForumInfo.ForumGroup.PrefixURL Is Nothing AndAlso Not String.IsNullOrEmpty(ForumInfo.ForumGroup.PrefixURL) Then
                        Pager1.BaseURL &= "/" & ForumInfo.ForumGroup.PrefixURL
                    End If
                    Pager1.BaseURL &= TopicURL
                    Pager1.PageMode = PagerNav.Mode.Links
                End If
            End If
            If Not Request.Params(ParamKeys.Sort) Is Nothing Then
                Dim Params As String() = {ParamKeys.Sort & "=" & Request.Params(ParamKeys.Sort)}
                Pager1.Params = Params
                If Not Pager2 Is Nothing Then
                    Pager2.Params = Params
                End If

            End If
            If Not Pager2 Is Nothing Then
                'If UseAjax Then
                'Pager2.PageMode = PagerNav.Mode.CallBack
                ' Else
                Pager2.PageMode = Modules.ActiveForums.Controls.PagerNav.Mode.Links ' DotNetNuke.Modules.ActiveForums.Controls.Pager.Mode.CallBack
                ' End If
                Pager2.PageCount = intPages
                Pager2.UseShortUrls = MainSettings.UseShortUrls
                Pager2.CurrentPage = PageId
                Pager2.TabID = CType(Request.Params("TabId"), Integer)
                Pager2.ForumID = ForumId
                Pager2.TopicId = TopicId
                ' Pager2.ClientScript = "afPageTopic({0});"
                Pager2.PageText = Utilities.GetSharedResource("[RESX:Page]")
                Pager2.OfText = Utilities.GetSharedResource("[RESX:PageOf]")
                Pager2.View = Views.Topic
                Pager2.PageMode = PagerNav.Mode.Links
                If MainSettings.URLRewriteEnabled Then
                    If Not String.IsNullOrEmpty(TopicURL) Then
                        If Not String.IsNullOrEmpty(MainSettings.PrefixURLBase) Then
                            Pager2.BaseURL = "/" & MainSettings.PrefixURLBase
                        End If
                        If Not ForumInfo.ForumGroup.PrefixURL Is Nothing AndAlso Not String.IsNullOrEmpty(ForumInfo.ForumGroup.PrefixURL) Then
                            Pager2.BaseURL &= "/" & ForumInfo.ForumGroup.PrefixURL
                        End If
                        Pager2.BaseURL &= TopicURL

                    End If
                End If

            End If

        End Sub
#End Region


    End Class
End Namespace